<template>
    <p>watch vs watchEffect</p>
    <p>{{ numberRef }}</p>
    <p>{{ name }} {{ age }}</p>
</template>

<script>
import { ref, toRefs, watch, reactive } from "vue";
export default {
    name: "Watch",
    setup() {
        // 定义值类型
        const numberRef = ref(100);
        const state = reactive({
            name: "大伟聊前端",
            age: 21,
        });

        // watch 监听
        watch(numberRef, (newNumber, oldNumber) => {
            console.log("ref watch", newNumber, oldNumber);
        });

        // 定时器，修改 numberRef 的值，用于监听
        setTimeout(() => {
            numberRef.value = 200;
        }, 1000);

        watch(
            // 第一个参数，确定要监听哪个属性
            () => state.age,

            // 第二个参数，回调函数
            (newAge, oldAge) => {
                console.log("state watch", newAge, oldAge);
            },

            // 第三个参数，配置项，可选
            {
                immediate: true, // 初始换之前就监听，可选
                deep: true, // 深度监听
            },
        );

        setTimeout(() => {
            state.age = 25;
        }, 3000);

        setTimeout(() => {
            state.name = "大伟聊前端111";
        }, 5000);
        return {
            numberRef,
            ...toRefs(state),
        };
    },
};
</script>
